package com.liu.my_blog_system.controller.admin;

import com.liu.my_blog_system.service.TbUploadFileService;
import com.liu.my_blog_system.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.List;

/**
 * @author liuchengjie
 */
@Api(tags = "文件接口")
@RestController
@RequestMapping("/admin/image")
public class UploadFileController {

    @Autowired
    private TbUploadFileService uploadFileService;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/uploadFile")
    public Result uploadImage(@RequestParam("file") @NotBlank(message = "文件不能为空") MultipartFile file) {
        Result result = null;
        try {
            result = uploadFileService.uploadFile(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 查看文件
     * @param imageId
     * @param openStyle
     * @param response
     */
    @ApiOperation(value = "查看文件")
    @GetMapping("viewFile")
    public void getImage(@RequestParam("fileId") String imageId,
                           @RequestParam("openStyle") String openStyle,
                           HttpServletResponse response) {
        try {
            uploadFileService.viewImage(imageId,openStyle,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 分页查询文件记录
     * @param current
     * @param size
     * @return
     */
    @ApiOperation(value = "分页获取文件列表")
    @GetMapping("/getFileList")
    public Result getFileList(@RequestParam("current") @NotBlank(message = "当前页不能为空") Long current,
                              @RequestParam("size") @NotBlank(message = "当前条数不能为空") Long size) {

        Result result = uploadFileService.findFileListPage(current, size);
        return result;
    }

    /**
     * 根据id删除文件记录
     * @param idList
     * @return
     */
    @ApiOperation(value = "根据id删除文件记录")
    @GetMapping("/deleteFileRecords")
    public Result deleteFileRecords(@RequestParam("idList") @NotBlank(message = "id不能为空") List<Long> idList) {
        boolean b = uploadFileService.removeByIds(idList);
        if (b) {
            return Result.ok().message("删除文件记录成功");
        }
        return Result.error().message("删除文件记录失败");
    }
}
